static void Main(string[] args)
{
HasCycle();
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
private static void HasCycle()
{
// 3 -> 2 -> 0 -> -4
ListNode head = new ListNode(3);
head.next = new ListNode(2);
head.next.next = new ListNode(0);
head.next.next.next = new ListNode(-4);
// 使得環 -4 指向 2
head.next.next.next.next = head.next;
bool result = HasCycle(head);
Console.WriteLine(result ? "有環." : "沒環");
Console.ReadKey();
}
public static bool HasCycle(ListNode head)
{
if (head == null || head.next == null)
{
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast)
{
if (fast == null || fast.next == null)
{
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}